package database

import (
	"log"
	"os"
	"time"

	_ "github.com/lib/pq"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"go_user_manager/pkg/framework"
	"go_user_manager/pkg/utils"
)

type GormConfig struct {
	MasterDNS string `yaml:"master_dns" mapstructure:"master_dns"`
	SlaverDns string `yaml:"slave_dns" mapstructure:"slaver_dns"`
}

func NewGorm(config framework.Configuration) *gorm.DB {
	gromConfig := utils.LoadConfig(config, GormConfig{}).(GormConfig)
	logConfig := logger.Config{
		SlowThreshold:             time.Second,
		LogLevel:                  logger.Info,
		ParameterizedQueries:      true,
		IgnoreRecordNotFoundError: false,
		Colorful:                  true,
	}
	sqlLog := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logConfig)
	db, err := gorm.Open(mysql.Open(gromConfig.MasterDNS), &gorm.Config{Logger: sqlLog})
	if err != nil {
		log.Panicf("连接数据库失败：%s", err)
	}
	return db
}
